package ui

import (
	"lnzw/common/proto/cs_gen"
	"lnzw/engine/actor"
	"lnzw/engine/log"
	"lnzw/server/test/test_fyne/test_3/transport"

	"fyne.io/fyne/v2"
	"fyne.io/fyne/v2/dialog"
	"go.uber.org/zap"
)

var offset_x = 150
var offset_y = 10

type MainUI struct {
	UIBase
	fyne.Container
	info    *InfoUI
	mapui   *MapUI
	loginui *LoginUI
}

func (m *MainUI) Init() {
	//m.Map = data
	//m.drawPanel()
	//m.AddMe()
	fcreatemap := EventHandle(m.OnCreateMap)
	GlobalEventMgr.Register(EventType_CreateMap, &fcreatemap)
	flogin := EventHandle(m.OnLogin)
	GlobalEventMgr.Register(EventType_Login, &flogin)
	m.info = NewInfoUI(m)
	m.info.Init()
	m.mapui = NewMapUI(m)
	m.mapui.Init()
	m.loginui = NewLoginUI(m)
	//m.loginui.Init()
}

func (m *MainUI) OnLogin(event IEvent) {
	msg := event.(*cs_gen.ResLogin)
	if msg.Result != cs_gen.ErrorCode_SUCCESS {
		dialog.ShowInformation("提示", "登录失败", m.Window)
		return
	}
	m.loginui.Close()
}

func (m *MainUI) OnCreateMap(event IEvent) {
	msg := event.(actor.Msg)
	rsp, err := transport.DefaultReceive(msg)
	if err != nil {
		log.Error("unmarshal failed", zap.Error(err))
		return
	}

	rspCreateMap := rsp.(*cs_gen.ResCreateMap)
	if rspCreateMap.Result != cs_gen.ErrorCode_SUCCESS {
		dialog.ShowInformation("提示", "创建地图失败", m.Window)
		return
	}
	GlobalEventMgr.Dispatch(EventType_GetMap, rspCreateMap.MapId)
}

func NewMainUI(mainWindow fyne.Window, app fyne.App) fyne.CanvasObject {
	ui := &MainUI{
		UIBase: UIBase{
			Window: mainWindow,
			App:    app,
		},
	}
	ui.UIBase.Container = &ui.Container
	ui.Init()
	return &ui.Container
}

// func (m *MainUI) AddMe() {
// 	x, y := m.Map.RandPosition()
// 	player := unit.NewPlayerUnit(data.GenUnitId(), x, y, viewrange)
// 	m.Map.EnterMap(player)
// 	playerui := NewPlayerUI(player, m.MainWindow, m.MainContainer)
// 	playerui.Me = true
// 	playerui.Init()
// 	go func() {
// 		for {
// 			playerui.Tick()
// 			time.Sleep(30 * time.Millisecond)
// 		}
// 	}()
// }
